/**
 * 洞察流程信息存储，对外提供获取流程节点配置参数的方法
 */
var MineFlowInfo = {};


/**
 * 挖掘洞察控制类
 * mode: 空值显示当前执行洞察信息还是成果分类的洞察信息
 * pid: 流程id或者成果id（mode为true）
 */
function ScheduleMineViewlingController(pid, mode, job, idx, jobId) {
    var parentHeight = $('#tempo-mine-viewing').height();
    var taskIsNotTrigger = job.failedCount == 0 && job.successCount == 0 && "manualExcute" != job.trigger.manualType
        && "atonceexcute" != job.trigger.excutetype;
    var mask = null;
    var insightCache = {};
    //遮罩
    var showMaskOpt = function (opt) {
        if (opt == 'show') {
            mask = $("<div/>").tempoprogressbar();
        } else {
            if (mask) {
                mask.tempoprogressbar('close');
            }
        }
    }
    var summarizeIsLoaded = false;
    // 成果分类展示洞察时，则启用新的url
    var getUrl = function (key, defaultValue) {
        var url = {
            "processInfo": "/api/ai/app/insight/get-process-info",
            "flowView": "/api/ai/app/insight/get-flow-info",
            "nodeInsight": "/api/ai/app/insight/list-node-info"
        };
        return (mode && url[key]) || defaultValue;
    }

    var bindEvent = function (data) {
        // 流程图点击事件
        $('body').off('click.insight').on('click.insight', nodeInsight);
        Eventbus.one('curTaskexecute.task', function (flowId) {
            if (summarizeIsLoaded) {
                return;
            }
            var process = $("<div/>").tempoprogressbar();
            //获取流程信息
            $.postForm({
                url: contextPath + getUrl("processInfo", "/api/ai/mine/searchProcessInsightInfo"),
                data: {
                    flowId: flowId,
                    serviceid: flowId
                },
                complete: function () {
                    process.tempoprogressbar("destroy");
                },
                success: function (result) {
                    if ($('#tempo-mine-viewing').length == 0) {
                        console.log('Nothing found.');
                        return;
                    }

                    if (result && result.success && result.data) {
                        result = result.data;
                        if (result.processData) {
                            result.processData = JSON.parse(result.processData);
                        }
                    }
                    var insightData = result.processData;
                    //流程描述
                    var showDesc = function (descDiv) {
                        var descData = insightData.desc;
                        descData.PNAME = result.PNAME;
                        descData.THEMENAME = result.THEMENAME;
                        rendOverViewDesc(descDiv, descData);
                    }
                    if (!result || !result.processData || !result.processData.desc || !result.processData.desc.durationTime) {
                    } else {
                        //综述tab页
                        addTab('desc', TempoUtils.locale("mine.summarize"), showDesc);
                    }
                }
            });
        });
    }

    /**
     * 流程图点击事件处理
     */
    var nodeInsight = function (event) {
        //如当前模式处于洞察的时候，则可请求加载数据，否则截断
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        if ('viewing' != analyseStatus.getType()) {
            return;
        }
        //如果是流程节点，显示节点洞察
        if (arguments.length > 2 && (arguments[1] == 'miningnode' || arguments[1] == 'subprocess')) {
            if (arguments.length == 4) {
                var tar = arguments[3];
                if (tar.attr("_widgetName") == 'minesubprocessnode') {
                    return;
                }
            }
            var eid = arguments[2];
            loadNodeInsight(eid)
        } else if ($(event.target).hasClass('tempo-mine-board-container') || $(arguments[0].target).hasClass('tempo-mine-board-container') || $(arguments[0].target).hasClass('tempo-board-container')) {
            //如果是空白部分，显示流程综述
            addTab('logger');
        }
    }

    /**
     * 获取节点洞察数据
     * 添加节点洞察缓存，减少不必要的请求
     */
    var loadNodeInsight = function (nodeid) {
        showMaskOpt('show');
        var show = function (result) {
            if (result && result.length > 0) {
                showNodeInsight(result);
            }
            showMaskOpt('hide');
        }
        if (insightCache[nodeid]) {
            var result = insightCache[nodeid];
            show(result);
            return;
        }
        //兼容API服务的serviceid
        $.postForm({
            url: contextPath + getUrl('nodeInsight', "/api/ai/mine/searchInsightNodeInfo"),
            data: {
                nodeId: nodeid,
                pid: jobId
            },
            success: function (result) {
                debugger
                if (result && result.success) {
                    result = result.data;
                }
                insightCache[nodeid] = result;
                show(result);
            },
            error: function () {

            }
        });
    }

    //显示节点洞察
    var showNodeInsight = function (result) {
        //获取节点id和名称
        var label = result[0].nodeLabel;
        var nodeId = result[0].nodeId;
        var insightInfo = JSON.parse(result[0].info);
        if (insightInfo.subInsight && insightInfo.subInsight == "off") {
            return;
        }
        //子流程需要双击打开选择节点才能显示
        if (result[0].nodeConfigId == 'subprocess') {
            return;
        }

        var show = function (container) {
            //端口标题栏
            var headerTab = $("<div>").appendTo(container).css({'margin-bottom': '10px', 'overflow': 'auto'});
            //端口洞察页面
            var contentTab = $("<div>").appendTo(container);
            // 对洞察展示的端口顺序进行排序，模型显示在前面，其他显示在后面
            var ports = [];
            var models = [];
            var isSortFlag = true;
            result.forEach(function (e) {
                var insightData = JSON.parse(e.info);
                if (insightData.cycleLabel && (insightData.cycleLabel).length > 0) {
                    isSortFlag = false;
                }
                if (e.portType == 'node_default') {
                    models.push(e);
                } else if (e.portType == 'model') {
                    models.push(e);
                } else {
                    ports.push(e);
                }
            })
            if (isSortFlag) {
                result = models.concat(ports);//顺序为节点 模型 数据集 解决bug7641
            }
            if (result != null && result.length > 1) {
                if (result[0].nodeConfigId == "apriori" || result[0].nodeConfigId == "fpgrowth") {
                    var compare = function (v1, v2) {
                        p1 = v1.port;
                        p2 = v2.port;
                        if (p1 == "exa") {
                            p1 = "n";
                        }
                        if (p2 == "exa") {
                            p2 = "n";
                        }
                        return p1 > p2
                    }
                    result.sort(compare);
                } else if (result[0].nodeConfigId == "textTF") {
                    var result_tf = [];
                    var out_tf = [];
                    var exa_tf = [];
                    var graph_tf = [];
                    result.forEach(function (e) {
                        if (e.port == 'graph') {
                            graph_tf.push(e);
                        } else if (e.port == 'exa') {
                            exa_tf.push(e);
                        } else if (e.port == 'out') {
                            out_tf.push(e);
                        }
                    })
                    var i = 0;
                    while (exa_tf[i] || out_tf[i] || graph_tf[i]) {
                        if (exa_tf[i]) {
                            result_tf.push(exa_tf[i]);
                        }
                        if (out_tf[i]) {
                            result_tf.push(out_tf[i]);
                        }
                        if (graph_tf[i]) {
                            result_tf.push(graph_tf[i]);
                        }
                        i++;
                    }
                    result = result_tf;
                }
            }

            for (var m = 0; m < result.length; m++) {
                //显示端口页面
                showPortView(headerTab, contentTab, container, result[m], window.constant.DATANODES.indexOf(result[m].nodeConfigId) == -1 || result[m].locType == 'result', result.length)
            }
            //触发第一个端口的显示事件
            headerTab.find('.tempo-mine-viewing-result-style:first').trigger('click');
        }
        //添加到tab页，并回掉show方法显示节点洞察内容
        addTab(nodeId, label, show)

    }
    //显示端口洞察
    var showPortView = function (headerTab, contentTab, container, insightResItem, isProcess, resultLen) {
        var portType = insightResItem.portType;
        if (!portType) {
            return;
        }
        var cycleLabel = "";
        var insightData = JSON.parse(insightResItem.info);
        if (insightData.cycleLabel && (insightData.cycleLabel).length > 0) {
            cycleLabel = "(" + (insightData.cycleLabel).replace("|", "-") + ")";
        }
        var isShowStatisticData = insightData.isShowStatisticData || insightData.showStatisticData;
        var resultStatisticData = insightData.resultStatisticData;
        var resultStatisticDataNom = insightData.resultStatisticDataNom;
        if (!isShowStatisticData) {
            if ((resultStatisticData && resultStatisticDataNom) && (resultStatisticData.length > 0 || resultStatisticDataNom.length > 0)) {
                isShowStatisticData = true;
            }
        }
        //数据集端口
        if (TempoMineUtils.isDataSet(portType)) {
            //如果是输入输出节点，则分开两个端口显示，一个原始数据，一个统计数据
            if (!isProcess) {
                $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem).text(TempoUtils.locale("mine.originalData") + cycleLabel).appendTo(headerTab).click(function () {
                    contentTab.empty();
                    selectHeader($(this));
                    var insightData = JSON.parse($(this).data('insightData').info);
                    createResTable(insightData, contentTab);
                })
                if (isShowStatisticData) {
                    $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem).text(TempoUtils.locale("mine.originalDataStatisticsInfo") + cycleLabel).appendTo(headerTab).click(function () {
                        selectHeader($(this));
                        contentTab.empty();
                        var insightData = JSON.parse($(this).data('insightData').info);
                        createResTableInfo1(insightData, contentTab, dataResultType.proceduce);
                    })
                }
            } else if (window.constant.TEXTMININGNODES.indexOf(insightResItem.nodeConfigId) != -1 || (insightData.nodeConfigId == "outlierdetection" && insightData.port == "out") || (insightData.nodeConfigId == "similaritiesmeasure" && insightData.port == "out")) {
                $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem)
                    .text((insightResItem.subProcessNodeId ? insightResItem.nodeLabel : '') + insightResItem.portLabel + cycleLabel).appendTo(headerTab)
                    .click(function (event) {
                        selectHeader($(this));
                        contentTab.empty();
                        var insightData = $(this).data('insightData');
                        //初始化算法参数界面
                        var pageParser = function (parent) {
                            return {
                                init: function (param) {
                                    param = param || {};
                                    var values = param.values || {};
                                    TempoUtils.parserUi(parent, values, $.noop);
                                }
                            }
                        }
                        var paramsConfig = MineFlowInfo.getParameters(insightData.nodeId);
                        $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightData.nodeConfigId].datasetInsightPage,
                            contentTab, insightData.nodeId, {
                                parameters: paramsConfig,
                                source: contentTab,
                                insight: JSON.parse(insightData.info),
                                pageParser: pageParser,
                                nodeId: insightData.nodeId
                            });
                    });
            } else {
                //其他节点的默认加载数据集
                $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem)
                    .text((insightResItem.subProcessNodeId ? insightResItem.nodeLabel : '') + getPortLabel(insightResItem) + cycleLabel).appendTo(headerTab)
                    .click(function (event) {
                        contentTab.empty();
                        selectHeader($(this));
                        var insightData = JSON.parse($(this).data('insightData').info);

                        if (insightData.nodeConfigId == "canonicalcorr") {
                            for (var x = 0; x < insightData.resultTableData.length; x++) {
                                var elem = insightData.resultTableData[x];
                                for (var y = 0; y < elem.length; y++) {
                                    if (elem[y] == "Eigenvalue" || elem[y] == "Proportion" || elem[y] == "Cumulation" || elem[y].indexOf("_correlation_coefficient") != -1) {
                                        var newelem = TempoUtils.locale("canonicalcorr." + elem[y]);
                                        insightData.resultTableData[x][y] = newelem;
                                    }
                                }
                            }
                        } else if (insightData.nodeConfigId == "anova") {
                            for (var x = 0; x < insightData.resultTableData.length; x++) {
                                var elem = insightData.resultTableData[x];
                                for (var y = 0; y < elem.length; y++) {
                                    if (elem[y] == "df" || elem[y] == "Sum_of_squares" || elem[y] == "Mean_square" || elem[y] == "F" || elem[y] == "sig") {
                                        var newelem = TempoUtils.locale("anova." + elem[y]);
                                        insightData.resultTableData[x][y] = newelem;
                                    }
                                }
                            }
                        }

                        var inputPanel = $('<span style="font-weight: bold;padding: 10px; cursor: pointer;font-size:14px;" id="inputPanel">' + TempoUtils.locale("mine.originalData") + '</span>').appendTo(contentTab);
                        if (isShowStatisticData) {
                            var sumPanel = $('<span style="font-weight: normal;padding: 10px; cursor: pointer;font-size:14px;" id="sumPanel">' + TempoUtils.locale("mine.originalDataStatisticsInfo") + '</span>').appendTo(contentTab);
                            sumPanel.click(function (e) {
                                rs.empty();
                                inputPanel.css('font-weight', 'normal');
                                sumPanel.css('font-weight', 'bold');
                                createResTableInfo1(insightData, rs, dataResultType.proceduce);
                            });
                        }
                        var rs = $('<div id="rs" style="margin-top: 10px;"></div>').appendTo(contentTab);
                        createResTable(insightData, rs);
                        rs.find('table:eq(0)').css('display', 'block');
                        rs.find('table:eq(1)').css('display', 'none');
                        inputPanel.click(function (e) {
                            rs.empty();
                            inputPanel.css('font-weight', 'bold');
                            if (sumPanel) {
                                sumPanel.css('font-weight', 'normal');
                            }
                            createResTable(insightData, rs);
                        });
                    });
            }
        } else if (TempoMineUtils.isModel(portType)) {

            $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem)
                .text((insightResItem.subProcessNodeId ? insightResItem.nodeLabel : '') + getPortLabel(insightResItem) + cycleLabel).appendTo(headerTab)
                .click(function (event) {

                    var insightInfo = $(this).data('insightData');
                    contentTab.empty();
                    selectHeader($(this));
                    //初始化算法参数界面
                    var pageParser = function (parent) {
                        return {
                            init: function (param) {
                                param = param || {};
                                var values = param.values || {};
                                TempoUtils.parserUi(parent, values, $.noop);
                            }
                        }
                    }
                    var configParentDiv = $('<div class="tempo-mine-alg-config-page">').appendTo(contentTab);
                    if (window.constant.INDIRECTLOADMNODES.indexOf(insightResItem.nodeConfigId) != -1) {
                        var paramsConfig = MineFlowInfo.getParameters(insightResItem.nodeId);
                        var insightData = JSON.parse(insightInfo.info);
                        var algNodeInsightInfo = insightData.algNodeModelInsightInfo;
                        while (algNodeInsightInfo.algNodeModelInsightInfo != null) {
                            algNodeInsightInfo = algNodeInsightInfo.algNodeModelInsightInfo;
                        }
                        if (algNodeInsightInfo != null) {
                            var algNodeConfigId = algNodeInsightInfo.producerNodeTypeId;
                            if (window.constant.CLUSTERNODES.indexOf(algNodeConfigId) != -1) {
                                if (window[window.constant.MNODES][algNodeInsightInfo.producerNodeTypeId].frameInsightPage) {
                                    var paramsConfig = MineFlowInfo.getParameters(algNodeInsightInfo.producerNodeId);
                                    if (paramsConfig) {
                                        var clusterNodeInsightDiv = $("<div/>").appendTo(configParentDiv);
                                        $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][algNodeInsightInfo.producerNodeTypeId].frameInsightPage,
                                            clusterNodeInsightDiv, algNodeInsightInfo.producerNodeId, {
                                                source: clusterNodeInsightDiv,
                                                insight: algNodeInsightInfo,
                                                parameters: paramsConfig,
                                                dialog: pageParser(clusterNodeInsightDiv)
                                            });
                                    }
                                }
                                showClusterResPic1(algNodeInsightInfo, configParentDiv);
                            } else if (window.constant.FEATUREREDUCENODES.indexOf(algNodeConfigId) != -1) {
                                $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][algNodeInsightInfo.producerNodeTypeId].datasetInsightPage, configParentDiv, algNodeInsightInfo.producerNodeId, {
                                    source: configParentDiv,
                                    insight: algNodeInsightInfo,
                                    dialog: pageParser(configParentDiv)
                                });
                            } else if ("autoclustering" == algNodeConfigId) {
                                showClusterResPic1(JSON.parse(insightInfo.info).algNodeModelInsightInfo, contentTab, "auto");
                            } else if (algNodeConfigId == "ahp" || algNodeConfigId == "fce") {
                                configParentDiv.empty();
                                var paramsConfig = MineFlowInfo.getParameters(algNodeInsightInfo.producerNodeId);
                                $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][algNodeInsightInfo.producerNodeTypeId].frameInsightPage, configParentDiv, algNodeInsightInfo.producerNodeId, {
                                    source: configParentDiv,
                                    insight: algNodeInsightInfo,
                                    parameters: paramsConfig,
                                    dialog: pageParser(configParentDiv)
                                });

                            } else {
                                var paramsConfig = MineFlowInfo.getParameters(algNodeInsightInfo.producerNodeId);
                                $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][algNodeInsightInfo.producerNodeTypeId].frameInsightPage, configParentDiv, insightData.algNodeModelInsightInfo.producerNodeId, {
                                    source: configParentDiv,
                                    insight: algNodeInsightInfo,
                                    parameters: paramsConfig,
                                    dialog: pageParser(configParentDiv)
                                });
                            }
                        }
                    } else if (window.constant.CLUSTERNODES.indexOf(insightResItem.nodeConfigId) != -1) {
                        if (insightResItem.nodeConfigId == 'vcluster') {
                            showClusterResPic1(JSON.parse(insightInfo.info), contentTab);
                            if (window[insightInfo.type][insightInfo.nodeConfigId].frameInsightPage) {
                                var paramsConfig = MineFlowInfo.getParameters(insightResItem.nodeId);
                                if (paramsConfig) {
                                    var clusterNodeInsightDiv = $("<div/>").appendTo(contentTab);
                                    $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightInfo.nodeConfigId].frameInsightPage,
                                        clusterNodeInsightDiv, insightResItem.nodeId, {
                                            source: clusterNodeInsightDiv,
                                            insight: insightInfo,
                                            parameters: paramsConfig,
                                            dialog: pageParser(clusterNodeInsightDiv)
                                        });
                                }
                            }
                        } else {
                            if (window[insightInfo.type][insightInfo.nodeConfigId].frameInsightPage) {
                                var paramsConfig = MineFlowInfo.getParameters(insightResItem.nodeId);
                                if (paramsConfig) {
                                    var clusterNodeInsightDiv = $("<div/>").appendTo(contentTab);
                                    $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightInfo.nodeConfigId].frameInsightPage,
                                        clusterNodeInsightDiv, insightResItem.nodeId, {
                                            source: clusterNodeInsightDiv,
                                            insight: insightInfo,
                                            parameters: paramsConfig,
                                            dialog: pageParser(clusterNodeInsightDiv)
                                        });
                                }
                            }
                            showClusterResPic1(JSON.parse(insightInfo.info), contentTab);
                        }
                    } else if (insightResItem.nodeConfigId == "pca" || insightResItem.nodeConfigId == "factor" || insightResItem.nodeConfigId == "svd" || insightResItem.nodeConfigId == "binning") {
                        selectHeader($(this));
                        contentTab.empty();
                        var insightData = $(this).data('insightData');
                        //初始化算法参数界面
                        var pageParser = function (parent) {
                            return {
                                init: function (param) {
                                    param = param || {};
                                    var values = param.values || {};
                                    TempoUtils.parserUi(parent, values, $.noop);
                                }
                            }
                        }
                        var paramsConfig = MineFlowInfo.getParameters(insightData.nodeId);
                        $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightData.nodeConfigId].datasetInsightPage,
                            contentTab, insightData.nodeId, {
                                parameters: paramsConfig,
                                source: contentTab,
                                insight: JSON.parse(insightData.info),
                                pageParser: pageParser,
                                nodeId: insightData.nodeId
                            });
                    } else if (insightResItem.nodeConfigId == "autoclustering") {
                        showClusterResPic1(JSON.parse(insightInfo.info), contentTab, "auto");
                    } else if (insightResItem.nodeConfigId == "pmmlapplymodel" || insightResItem.nodeConfigId == "readpmmlmodel") {
                        var insightData = JSON.parse(insightInfo.info);
                        var algNodeInsightInfo = insightData.algNodeModelInsightInfo;
                        while (algNodeInsightInfo.algNodeModelInsightInfo != null) {
                            algNodeInsightInfo = algNodeInsightInfo.algNodeModelInsightInfo;
                        }
                        showPMMLModelInsight(algNodeInsightInfo, contentTab);
                    } else {
                        var paramsConfig = MineFlowInfo.getParameters(insightResItem.nodeId);
                        if (paramsConfig && window[window.constant.MNODES][insightResItem.nodeConfigId].frameInsightPage) {
                            contentTab.empty();
                            $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightResItem.nodeConfigId].frameInsightPage, contentTab, insightResItem.nodeId, {
                                source: contentTab,
                                insight: JSON.parse(insightInfo.info),
                                parameters: paramsConfig,
                                dialog: pageParser(contentTab)
                            });
                        }
                    }
                });
        } else if (!TempoMineUtils.isNotDefaultPort(portType)) {
            $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem)
                .text((insightResItem.subProcessNodeId ? insightResItem.nodeLabel : '') + TempoUtils.locale("mine.jiedian") + cycleLabel).appendTo(headerTab)
                .click(function (event) {
                    selectHeader($(this));
                    contentTab.empty();
                    var insightInfo = $(this).data('insightData');
                    var insightData = JSON.parse(insightInfo.info);
                    contentTab.empty();
                    var paramsConfig = MineFlowInfo.getParameters(insightInfo.nodeId)
                    $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightInfo.nodeConfigId].frameInsightPage,
                        contentTab, insightInfo.nodeId, {
                            source: contentTab,
                            insight: insightData,
                            parameters: paramsConfig
                        });
                });
        } else if (TempoMineUtils.isGraph(portType)) {
            $("<span class='tempo-mine-viewing-result-style' style='display: inline-block;'>").data('insightData', insightResItem)
                .text((insightResItem.subProcessNodeId ? insightResItem.nodeLabel : '') + getPortLabel(insightResItem) + cycleLabel).appendTo(headerTab)
                .click(function (event) {
                    selectHeader($(this));
                    contentTab.empty();
                    var insightInfo = $(this).data('insightData');
                    var insightData = JSON.parse(insightInfo.info);
                    contentTab.empty();
                    var paramsConfig = MineFlowInfo.getParameters(insightInfo.nodeId);
                    $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[window.constant.MNODES][insightInfo.nodeConfigId].frameInsightPage,
                        contentTab, insightInfo.nodeId, {
                            source: contentTab,
                            insight: insightData,
                            parameters: paramsConfig
                        });
                });
        } else {
            var insightResItem = event.data;
            var insightId = $(this).data('insightId');
            getPortInsight(insightId, function (insightInfo) {
                var insightInfo = event.data[0];
                var insightResItem = event.data[1];
                $m.loadHtmlSyn(contextPath + '/api/ai/mine/' + window[insightInfo.type][insightInfo.nodeConfigId].frameInsightPage,
                    oDivData, insightResItem.nodeId, {source: oDivData, insight: insightInfo});
            })
        }
        if (resultLen > 20) {
            headerTab.find(".tempo-mine-viewing-result-style").css("width", 60);
            headerTab.find(".tempo-mine-viewing-result-style").css({"border-left": "none"});
        }
    }


    /**
     * 缓存流程信息，用来节点信息获取
     * */
    var cacheFlowData = function (param) {
        var flowData = null;
        try {
            flowData = JSON.parse(param);
        } catch (e) {
            return {};
        }
        var data = processChildrenPosition(flowData.children);
        MineFlowInfo = (function () {
            return {
                getParameters: function (id) {
                    /**
                     * 获取节点配置信息（包含子流程内部节点）
                     */
                    var _findData = function (pathId, navData) {
                        var navId = navData.eid;
                        if (navId == pathId) {
                            return navData.parameters;
                        } else {
                            if (navData.process) {
                                navId = navData.process.id;
                                navData = navData.process.flow;
                            }
                            if (navData && navData.children) {
                                var navs = navData.children;
                                if (navs) {
                                    for (var i = 0; i < navs.length; i++) {
                                        var nav = navs[i];
                                        var data = _findData(pathId, nav);
                                        if (data != null) {
                                            return data;
                                        }
                                    }
                                }
                            }
                        }
                    };
                    if (flowData && flowData.children) {
                        return _findData(id, flowData);
                    }
                    return {};
                }
            }
        })();
    }

    var showLogger = function (descDiv) {
        debugger
        var refreshLogger = function (exeId) {
            if (exeId == null) {
                exeId = TempoUtils.uuid();
            }
            var flowpanel = $('#fc-flowgraph');
            var spanel = $(".tempo-mine-logger");
            var exid = exeId.split(",")[idx];
            var logger = spanel.taskflowlogger({
                title: "日志下载",
                parent: spanel,
                mineServiceInfo: null,
                exid: exid,
                taskIsNotTrigger: taskIsNotTrigger,
                flowpanel: flowpanel
            });
            logger.taskflowlogger("clear");
            if (taskIsNotTrigger) {
            } else {
                $.ajax({
                    url: contextPath + "/api/ai/mine/process/getExecuteStatusLog",
                    data: {
                        exid: exid,
                    },
                    type: 'post',
                    success: function (result) {
                        debugger
                        if ("FINISHED" != result.status) {
                            logger.taskflowlogger('showLog', "正在准备");
                        }
                        logger.taskflowlogger("startLogging", {
                            exid: exid,
                            flowId: job.id,
                            serviceid: pid,
                            mineServiceInfo: null,
                            flowpanel: flowpanel
                        });
                    }
                });
            }
        }
        var refreshParentDiv = $("<div>").appendTo(descDiv);
        /*var refreshDiv = $("<div style='float:right;padding-top: 4px;padding-right: 5px;'></div>").appendTo(refreshParentDiv);
        var refreshSelect = $("<select name='refresh'></select>").appendTo(refreshDiv);
        $('<option value="autorefresh">自动刷新</option>').appendTo(refreshSelect);
        $('<option value="manualrefresh">手动刷新</option>').appendTo(refreshSelect);
        var refreshBtn = $('<span class="ui-icon ui-icon tempo-ui-icon tempo-ui-icon-refresh"></span>').appendTo(refreshDiv);*/
        var loggerParentDivHeight = parentHeight * 0.4;
        debugger
        var loggerParentDiv = $('<div style="width:100%;height:' + loggerParentDivHeight + 'px;"></div>').appendTo(refreshParentDiv);
        $('<div class="tempo-mine-logger tempo-panel"></div>').appendTo(loggerParentDiv);
        /*refreshSelect.selectmenu({
            width:100,
            change:function(event, ui){
                var value = ui.item.value;
                if (value == "autorefresh") {
                    refreshBtn.hide();
                    refreshLogger(job.exeId);
                } else {
                    refreshBtn.show();
                }
            }
        });
        if (refreshSelect.val() == "autorefresh") {
            refreshLogger(job.exeId);
            refreshBtn.hide();
        }*/
        if (job.logs && job.logs.length > 0) {
            refreshLogger(job.id + "_" + job.logs[0].id);
        } else {
            refreshLogger(job.exeId);
        }

        /*refreshBtn.unbind("click").bind("click",function(){
            refreshLogger(job.exeId);
        });*/
    }
    //初始化流程
    var initFlow = function () {
        debugger
        var panel = $("#tempo-mine-viewing-flowpanel");
        if (!panel || panel.size() == 0) {
            panel = $('#fc-flowgraph');
            if (panel.hasClass('tempo-mine-flow-container')) {
                panel.flowpanel('destroy');
            }
        }
        var tabs = $('#tempo-mine-viewing-resultshow');
        if (tabs.hasClass('tempo-tabs') && tabs.hasClass('ui-tabs')) {
            tabs.tabs("destroy");
        }
        if ($('#tempo-mine-viewing').length == 0) {
            console.log('Nothing found.');
            return;
        }
        var process = $("<div/>").tempoprogressbar();
        //获取流程信息
        $.postForm({
            url: contextPath + getUrl("processInfo", "/api/ai/mine/searchProcessInsightInfo"),
            data: {
                flowId: job.id,
                serviceid: pid
            },
            complete: function () {
                process.tempoprogressbar("destroy");
            },
            success: function (result) {
                if ($('#tempo-mine-viewing').length == 0) {
                    console.log('Nothing found.');
                    return;
                }

                if (result && result.success && result.data) {
                    result = result.data;
                    if (result.processData) {
                        result.processData = JSON.parse(result.processData);
                    }
                }

                var insightData = result.processData;
                //流程面板
                panel.flowpanel({
                    withLogger: false,
                    id: 'flowgraph',
                    customBtns: [{
                        text: TempoUtils.locale("mine.fangda"),
                        icon: 'ui-icon tempo-ui-icon tempo-ui-icon-insight-zoomout tempo-mine-button',
                        click: function () {
                            var zoom = panel.flowpanel('option', 'transform') || 100;
                            panel.flowpanel('option', 'transform', zoom + 10)
                            panel.flowpanel('zoomBorder');
                        }
                    }, {
                        text: TempoUtils.locale("mine.suoxiao"),
                        icon: 'ui-icon tempo-ui-icon tempo-ui-icon-insight-zoomin tempo-mine-button',
                        click: function () {
                            var zoom = panel.flowpanel('option', 'transform') || 100;
                            panel.flowpanel('option', 'transform', zoom - 10)
                            panel.flowpanel('zoomBorder');

                        }
                    }, {
                        icon: 'split-btn',
                        type: 'spliter'
                    }
                        , {
                            icon: 'ui-icon tempo-ui-icon tempo-mine-button tempo-ui-icon-uparrows-undertint',
                            click: function () {
                                var icon = $(this).find('span');
                                if (icon.hasClass('tempo-ui-icon-uparrows-undertint')) {
                                    icon.removeClass('tempo-ui-icon-uparrows-undertint');
                                    icon.addClass('tempo-ui-icon-downarrows-undertint');
                                    panel.layout().close('center');
                                    $('#tempo-mine-viewing').layout().sizePane('north', 32);
                                } else {
                                    icon.removeClass('tempo-ui-icon-downarrows-undertint');
                                    icon.addClass('tempo-ui-icon-uparrows-undertint');
                                    $('#tempo-mine-viewing').layout().sizePane('north', parentHeight * 0.48);
                                }
                            }
                        }]
                });

                var icon = panel.find('.tempo-ui-icon-uparrows-undertint');
                if (icon && icon.size() > 0) {
                    icon.removeClass('tempo-ui-icon-downarrows-undertint');
                    icon.addClass('tempo-ui-icon-uparrows-undertint');
                    $('#tempo-mine-viewing').layout().sizePane('north', parentHeight * 0.48);
                }
                //绘制流程图
                loadInputdata(pid, panel.flowpanel('getBoard'), cacheFlowData, panel);
                tabs.append('<ul>');
                tabs.tabs({
                    heightStyleType: 'fill',
                    activate: function (event, ui) {
                        var nodeid = ui.newPanel.attr('id');
                        panel.find('.tempo-basenode-select').removeClass('tempo-basenode-select');
                        panel.find('#' + nodeid).addClass('tempo-basenode-select');

                    }
                });
                if (!result || !result.processData || !result.processData.desc || !result.processData.desc.durationTime) {
                } else {
                    summarizeIsLoaded = true;
                }
                addTab('logger', "日志", showLogger);
                //流程描述
                var showDesc = function (descDiv) {
                    var descData = insightData.desc;
                    descData.PNAME = result.PNAME;
                    descData.THEMENAME = result.THEMENAME;
                    rendOverViewDesc(descDiv, descData);
                }
                if (!result || !result.processData || !result.processData.desc || !result.processData.desc.durationTime) {
                } else {
                    //综述tab页
                    addTab('desc', TempoUtils.locale("mine.summarize"), showDesc);
                }
            }
        });

    }

    //添加tab页
    var addTab = function (id, name, callback) {
        var tabs = $('#tempo-mine-viewing-resultshow');
        var lis = tabs.find('.ui-tabs-nav li');
        var li = tabs.find(".ui-tabs-nav li[aria-controls='" + id + "']");
        var index = lis.index(li);
        //如果已存在，则切换到该tab页
        if (index > -1) {
            tabs.tabs("option", "active", index);
        } else {
            if (!name || !id) return;
            var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon tempo-ui-icon tempo-ui-icon-remove' role='presentation'>Remove Tab</span></li>";
            if (id == 'desc' || id == "logger") {
                tabTemplate = "<li><a href='#{href}'>#{label}</a></li>";
            }
            var label = name,
                id = id,
                li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label.replace(/</g, "&lt;")));
            tabs.find(".ui-tabs-nav").append(li);
            var descDiv = $("<div id='" + id + "'></div>");
            tabs.append(descDiv);
            callback(descDiv);
            tabs.tabs("refresh");
            if (tabs.find(".ui-tabs-nav li").size() - 1 == 1) {
                tabs.tabs("option", "active", 0);
            } else {
                tabs.tabs("option", "active", tabs.find(".ui-tabs-nav li").size() - 1);
            }

            tabs.delegate("span.tempo-ui-icon-remove", "click", function () {
                var panelId = $(this).closest("li").remove().attr("aria-controls");
                tabs.find("#" + panelId).remove();
                tabs.tabs("refresh");
            });
        }
    }

    var selectHeader = function (target) {
        if (!$(target).hasClass('tempo-mine-viewing-result-style-sel')) {
            $(target).addClass('tempo-mine-viewing-result-style-sel');
        }
        $(target).siblings().removeClass('tempo-mine-viewing-result-style-sel');
    }


    var init = function () {
        initFlow();
        bindEvent();
    }

    //绘制流程图
    var loadInputdata = function (pid, board, callback, panel) {
        var pro = $("<div/>").tempoprogressbar();
        $.postForm({
            url: contextPath + "/api/ai/app/schedule/get-flow-info",
            data: {
                flowId: pid,
                serviceid: pid
            },
            success: function (params) {
                if (params && params.success) {
                    params = params.data;
                }
                if (callback) callback(params)
                renderBoard(params || JSON.stringify({}), board);
                if (panel) {
                    panel.flowpanel('setNavigatorRoot')
                    panel.flowpanel('loaded');
                }
                if (taskIsNotTrigger || "manualExcute" == job.trigger.manualType) {
                    var flowNodes = panel.find(".tempo-mining-tool-config-led");
                    flowNodes.removeClass('SUCCESS')
                }
            },
            complete: function () {
                pro.tempoprogressbar("close");
            },
            error: function () {

            }
        });
    }

    //初始化
    init();
}

window.ScheduleMineViewlingController = ScheduleMineViewlingController;